import 'dart:async';
import 'dart:convert';

import 'package:aichat_flutter_wallet/module/module_browser/pages/root_browser_page.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:flutter/material.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_network/http_manager.dart';
import 'package:lib_util/lib_util.dart';

import '../../app_config.dart';
import '../../kai_print.dart';
import '../../module/module_dapp/pages/dapp_page.dart';
import '../../module/module_dapp/provider/dapp_cache_provider.dart';
import '../../module/module_dapp/provider/dapp_provider.dart';
import '../../module/module_integral/pages/integral.dart';
import '../../module/module_news/pages/news_detail.dart';
import '../../module/module_news/widget/new_commemt_widget.dart';
import '../../module/module_trade/pages/trade_transaction_details.dart';
import '../../module/module_user_info/pages/fans.dart';
import '../../module/module_wallet/pages/wallet.dart';
import '../../module/module_wallet/provider/wallet_assets_provider.dart';
import '../../module/module_wallet/provider/wallet_index_provider.dart';
import '../bridge/native_channel_bridge.dart';
import '../mpc_help/chainListTool.dart';
import '../network/http_api.dart';
import '../network/http_chain_list.dart';
import '../provider/token_list_provider.dart';
import '../provider/user_settings_provider.dart';
import '../provider/wallect_connect_provider.dart';
import '../provider/wallet_info_provider.dart';
import '../utils/task_code_to_flutter.dart';
import '../widgets/dialog/easyloading.dart';
import '../widgets/loading/loading_weiget.dart';
import '../widgets/public_tip/public_tip.dart';
import 'routers.dart';

// 继承 wallect connet 的 抽象 类 并使用 其中的方法
class RootPage extends StatefulWidget {
  RootPage({Key? key});
  // 粉丝
  @override
  _RootPageState createState() => _RootPageState();
}
// with RouteAware
class _RootPageState extends State<RootPage>  {
  late StreamSubscription walletSubscription;
  late StreamSubscription walletSubscription2;
  RootPageType rootPageType = RootPageType.Wallet;

  // 粉丝？
  final GlobalKey<FansPageState> fansPageKey = GlobalKey<FansPageState>();
  final GlobalKey<IntegralPageState> integralPageKey = GlobalKey<IntegralPageState>();
  final GlobalKey<DappPageState> dappPageKey = GlobalKey<DappPageState>();
  final GlobalKey<NewsDetailState> newsDetailPageKey = GlobalKey<NewsDetailState>();



  bool isSetUserId = false;
  String capitalizeFirstLetter(String input) {
    if (input.isEmpty) {
      return input;
    }
    return input[0].toUpperCase() + input.substring(1);
  }

  RootPageType getPageType(String value) {
    switch (value) {
      case 'Dapp':
        return RootPageType.Dapp;
      case 'Wallet':
        return RootPageType.Wallet;
      case 'Integral':
        return RootPageType.Integral;
      case 'Fans':
        return RootPageType.Fans;
      case 'Follow':
        return RootPageType.Follow;
      case 'News':
        return RootPageType.NewsDetail;
      case 'Comment':
        return RootPageType.Comment;
      case 'Empty':
        return RootPageType.Empty;
      case 'Browser':
        return RootPageType.Browser;
      default:
        return RootPageType.Wallet;
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initPage();
    // 初始化 页面 参数
    walletSubscription = eventBus.on<GoNativeScanResult>().listen((event) {
      kaiPrint('Scan result show:  ${event.data} ');
      initWcc(event.data);
    });
    // 初始化 页面 参数
    walletSubscription2 = eventBus.on<ClickTabInEvent>().listen((event) {
      kaiPrint('views will be show:  ${event.data.page} ');
      initPage();
    });
  }

  initWcc(String url) async {
    try{
      await Provider.of<WCProviderNotifier>(context, listen: false);
      await context.read<WCProviderNotifier>().initProvider(url);
    }catch(e){
      kaiPrint('catch $e');
    }
  }

  initPage() async {
    //刷新钱包页面状态  更新钱包状态
    final userId = NativeChannelBridge.instance.appCommMsg?.userId;
    if (userId != '0' && userId != null && userId!.isNotEmpty) {
      final page = NativeChannelBridge.instance.appCommMsg?.page;
      rootPageType = getPageType(capitalizeFirstLetter(page!));
      initProvider().then((isBool){
        kaiPrint('[eventBus   ] done  ：${isBool}');
        this.isSetUserId = true;
        updateChildPageInfo();
        if (mounted) setState(() {});
      });
    }
  }

  updateChildPageInfo(){
    final value = rootPageType;
    switch (value) {
      case RootPageType.Fans || RootPageType.Follow:
        final parameter = NativeChannelBridge.instance.appCommMsg!.parameter;
        final userId = NativeChannelBridge.instance.appCommMsg!.userId;
        Map<String, dynamic> pageParameter = {'username': '',"userId": userId};
        if (parameter != null) {
          pageParameter = jsonDecode(parameter);
        }
        return  fansPageKey.currentState?.initPage(
          params: rootPageType== RootPageType.Fans? 'Fans':'Follow',
          userName: pageParameter['username'],
          uid: pageParameter['userId']
        );
      case RootPageType.Integral:
        return integralPageKey.currentState?.initPage();
      case RootPageType.Dapp:
        final parameter = NativeChannelBridge.instance.appCommMsg!.parameter;
        Map<String, dynamic> pageParameter = {'url': ''};
        if (parameter != null) {
          pageParameter = jsonDecode(parameter);
        }
        return dappPageKey.currentState?.initPage(pageParameter['url']);
      case RootPageType.Wallet:
        final parameter = NativeChannelBridge.instance.appCommMsg!.parameter;
        Map<String, dynamic> pageParameter = {};
        if (parameter != null) {
          pageParameter = jsonDecode(parameter);

          kaiPrint('pageParameter[transaction] ${pageParameter['transaction']}');

          if(pageParameter['transaction']!=null){
            final data= pageParameter['transaction'];
            final tokenInfo = data['token'];
            var walletInfoId= Provider.of<TokenListNotifier>(context, listen: false).walletInfoId;
            TransactionBean transactionInfo = TransactionBean(
                pending: false,
                state: '1',
                txId: data['transaction']['txId'],
                transactionTime: data['transaction']['created_at'],
                from: data['transaction']['from'],
                to: data['transaction']['to'],
                amount: data['transaction']['amount'],
                tokenContractAddress: tokenInfo['contract']??'');
            //  判断主流币 还是 代币
            var token= new Token(
              id: 10086,
              walletInfoId: walletInfoId,
              contractType: tokenInfo['contract'].isEmpty?TokenType.native.name:TokenType.token20.name,
              contract: tokenInfo['contract'],
              name:tokenInfo['name'],
              decimals: tokenInfo['decimal'],
              symbol: tokenInfo['symbol'],
              logo: tokenInfo['logo'],
              balance: tokenInfo['balance'],
            );
            Chain? chainItem = ChainList().chains.firstWhereOrNull((el)=> el.evmInfo?.chainId.toString()==data['chainId'].toString())??null;
            if(chainItem == null){
              return Toast.show(context, message: 'The rpc url address cannot be found',status:
              '-1');
            }
            String rpc= chainItem.evmInfo!.rpcList[0];
            String parentSymbol= chainItem.symbol;
            Navigator.of(context).push(MaterialPageRoute(
                settings: RouteSettings(name: Routes.transactionDetails),
                builder: (_) {
                  return TradeTransactionsPageDetails(
                      token: token, transaction: transactionInfo,
                      rpc:rpc,
                    parentSymbol:parentSymbol,
                    chainItem:chainItem,
                  );
                },));
            return;
          }
          if(pageParameter['toAddress'] == null){
            return '';
          }
          return TaskCodeToFlutter.linkToPage('306', toAddress: pageParameter['toAddress']??'');;
        }
        return '';

      default:
        return '';
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // AppRouterPageUtils().routeObserver.subscribe(this, ModalRoute.of(context)!);
    var config = AppConfig.of(context);
    if (config?.flavorName == 'development') {
      initPage();
    }
  }
  // @override
  // void deactivate() {
  //   super.deactivate();
  //   // 进入页面重新拉取学习时长
  //   kaiPrint('deactivate ${ModalRoute.of(context)?.isCurrent}');
  //   kaiPrint(ModalRoute.of(context)?.isCurrent);
  // }

  // @override
  // void didPush() {
  //   final route = ModalRoute.of(context)?.settings.name;
  //   print('A-didPush route: $route');
  //
  // }
  //
  // @override
  // void didPopNext() {
  //   final route = ModalRoute.of(context)?.settings.name;
  //   print('A-didPopNext route: $route');
  //   kaiPrint(ModalRoute.of(context)?.isCurrent);
  // }
  //
  // @override
  // void didPushNext() {
  //   final route = ModalRoute.of(context)?.settings.name;
  //   print('A-didPushNext route: $route');
  //   kaiPrint('isNow? ${ModalRoute.of(context)?.isCurrent}');
  // }
  //
  // @override
  // void didPop() {
  //   final route = ModalRoute.of(context)?.settings.name;
  //   print('A-didPop route: $route');
  // }


  Future<bool> initProvider() async {
    try {
      final userId = NativeChannelBridge.instance.appCommMsg?.userId;
      // 初始化
      WalletInfo? walletInfo = ObjectBox().getCurrentWalletInfo(userId!);
      // 初始化 密码库
      context.read<UserSettingsProvider>().initData(userId);
      context.read<WalletAssetsProvider>().setInitAssetsShowState();
      if (rootPageType == RootPageType.Dapp) {
        context.read<DAppProvider>().initData(userId);
        context.read<DAppCacheProvider>().initData(userId);
      }
      List<Chain> cacheList = await SP().getKeyChainsList();
      if (ChainList().chains.length <= 0 && cacheList.isNotEmpty) {
        ChainList().setChainsList(cacheList);
        ChainListTool.setWCChainList(cacheList);
       }
      HttpChainList().getSaltByUrl().then((value) {
        if (value != null) {
          SP().setRandomSalt(value);
        }
      });
      if (walletInfo != null) {
        // 重新创建
        await Provider.of<WalletInfoNotifier>(context, listen: false).setWalletInfo(walletInfo);
      }
      Provider.of<WalletIndexProvider>(context, listen: false).isSetWallet = walletInfo != null;
      if (ChainList().chains.length <= 0 || isSetUserId == false) {
        return HttpChainList().loadChainList();
      }
      return true;
    } catch (e) {
      kaiPrint('initProvider  error: ${e.toString()}');
      return false;
    }
  }

  @override
  void dispose() {
    /// 取消路由订阅
    super.dispose();
    walletSubscription.cancel();
    walletSubscription2.cancel();
    /// 取消路由订阅
    // AppRouterPageUtils().routeObserver.unsubscribe(this);
    try{
      // 销毁
      if(context.read<WCProviderNotifier>().getWeb3Wallet!=null){
        context.read<WCProviderNotifier>().onDispose();
      }
    }catch(e){
      kaiPrint('dispose $e');
    }
  //   销毁 wallectconnect  钱包 的链接
  }

  @override
  Widget build(BuildContext context) {
    if(isSetUserId==false){
      return Stack(
        children: [
          LoadingWidget()
        ],
      );
    }
    // 粉丝 页面
    switch (rootPageType) {
      // 粉丝 页面
      case RootPageType.Fans || RootPageType.Follow:
        final parameter = NativeChannelBridge.instance.appCommMsg!.parameter;
        final userId = NativeChannelBridge.instance.appCommMsg!.userId;
        Map<String, dynamic> pageParameter = {'username': '',"userId": userId};
        if (parameter != null) {
          pageParameter = jsonDecode(parameter);
        }
        return FansPage(
          key: fansPageKey,
          title: pageParameter['username'],
          userId: pageParameter['userId']
        );
      //   评论
      case RootPageType.Comment:
        final parameter = NativeChannelBridge.instance.appCommMsg!.parameter;
        Map<String, dynamic> pageParameter = {'type': null, 'id': null, 'toName': ''};
        if (parameter != null) {
          pageParameter = jsonDecode(parameter);
        }
        return Scaffold(
          backgroundColor: Colors.black.withOpacity(0.15),
          bottomNavigationBar: NewCommemtWidget(
            toName : pageParameter['toName'],
            onConfirm:(CommemtTypeCallBackData value) {
              EasyLoading.generateLoadingFuture(
                  HttpManager().post(API.doComment, {
                    'content': value.content ,
                    "target_type": pageParameter['type'],
                    'article_id': pageParameter['id'],
                    "target_id":  '',
                    'type': 0,
                    "images": value.images,
                    'videos': value.videos
                  })
              ).then((value){
                bool isLast = !Navigator.canPop(context);
                if (!isLast) {
                  Navigator.pop(context);
                }
                NativeChannelBridge().closeFlutterPage(num: 1);
                NativeChannelBridge().flGoCommentSuccess(pageParameter['type'].toString(),pageParameter['id'].toString(),'comment');
                rootPageType = RootPageType.Empty;
                if(mounted)setState(() {
                });
              }).catchError((error){
                Toast.show(context,
                    message:"Error: ${error.toString()}", status: '2');
              });
            },
            closeCallback: (){
              bool isLast = !Navigator.canPop(context);
              if (!isLast) {
                Navigator.pop(context);
              }
              NativeChannelBridge().closeFlutterPage(num: 1);
              rootPageType = RootPageType.Empty;
              if(mounted)setState(() {
              });
            },
          ),
        );
      case RootPageType.Dapp:
        final parameter = NativeChannelBridge.instance.appCommMsg!.parameter;
        Map<String, dynamic> pageParameter = {'url': ''};
        if (parameter != null) {
          pageParameter = jsonDecode(parameter);
        }
        return DappPage(key: dappPageKey,uri: pageParameter['url']??'',);
      //   钱包页面 页面
      case RootPageType.Wallet:
        return WalletPage();
      //  积分页面
      case RootPageType.Integral:
        return IntegralPage(
          key: integralPageKey,
        );
      //   资讯详情 + 评论
      case RootPageType.NewsDetail:
        final parameter = NativeChannelBridge.instance.appCommMsg!.parameter;
        Map<String, dynamic> pageParameter = {'type': null, 'id': null};
        if (parameter != null) {
          pageParameter = jsonDecode(parameter);
        }
        return NewsDetailPage(
          key: newsDetailPageKey,
          target_type: pageParameter['type'] != null
              ? int.parse(pageParameter['type'].toString())
              : 1,
          id: pageParameter['id'] ?? '525409958110021',
          onClose:(){
            rootPageType = RootPageType.Empty;
            if(mounted)setState(() {
            });
          }
        );
      case RootPageType.Empty:
        return Container(
          color: Colors.transparent,
        );
      // case RootPageType.Wcc:
      //   return WCCPage(
      //     onClose: (){
      //       NativeChannelBridge.instance.closeFlutterPage(num:1);
      //       rootPageType = RootPageType.Empty;
      //       if(mounted)setState(() {
      //       });
      //     },
      //   );
      case RootPageType.Browser:
        final parameter = NativeChannelBridge.instance.appCommMsg!.parameter;
        Map<String, dynamic> pageParameter = {'url': 'https://www.baidu.com'};
        if (parameter != null) {
          pageParameter = jsonDecode(parameter);
        }
        return RootBrowserPage(
          url: pageParameter['url'],
          onClose:(){
            NativeChannelBridge.instance.closeFlutterPage(num:1);
              rootPageType = RootPageType.Empty;
              if(mounted)setState(() {
              });
          }
        );
      default:
        return WalletPage();
    }
  }
}
